rm(list=ls())

##############################################################################
# APPENDIX B1 FIGURE 1
##############################################################################

# load packages
#library(texreg)
#library(MASS)

# load data 
load("data/eurepoc_year_attacks.RData")

##############
# RUN MODELS #
##############

#model 1 (all-country)
neg_binom1 <- glm.nb(attacks ~ candidate + percent_usage + time,
                     data = eurepoc_year_data, link = log, control=glm.control(maxit=20))
#summary(neg_binom1)

#model 2 (25 percent usage)
mean_percent_usage <- aggregate(eurepoc_year_data$percent_usage, 
                                by = list(eurepoc_year_data$ccode), mean, na.rm =T)
names(mean_percent_usage)[2] <- "mean_percent_usage"

country_year_attacks <- merge(eurepoc_year_data, mean_percent_usage, by.x = "ccode", by.y = "Group.1", all.x = T) 
usage_year_attacks <- subset(eurepoc_year_data, mean_percent_usage > 25)

neg_binom2 <- glm.nb(attacks ~ candidate + percent_usage + time,
                     data = usage_year_attacks, link = log, control=glm.control(maxit=100))

#summary(neg_binom2)
####CHECK THIS IT NEEDS TO BE UPDATED IN PAPER 

#model 3 (candidate-only)
#create only candidate within data set 
SY_within <- subset(eurepoc_year_data, candidate == 1)

#create ITU candidate binary
SY_within$ccode_year <- paste(SY_within$ccode, SY_within$year, sep="_")
unique_ITU_year <- as.data.frame(table(SY_within$ccode_year))
unique_ITU_year <- separate(unique_ITU_year, col = Var1, into = c("ccode", "year"), 
                            sep = "_")
candidate_vector <- unique(unique_ITU_year$ccode)
candidate_year_attacks <- country_year_attacks[country_year_attacks$ccode %in% candidate_vector,]

neg_binom3 <- glm.nb(attacks ~ candidate + percent_usage + time,
                     data = candidate_year_attacks, link = log, control=glm.control(maxit=20))
#summary(neg_binom3)

################
# CREATE TABLE #
################

appendB1_tab1 <- screenreg(list(neg_binom1, neg_binom2, neg_binom3), custom.coef.map = list("candidate" = "candidate", 
"percent_usage" = "internet usage", "time" = "time"))

print(appendB1_tab1)

# script complete message 
print("appendB1_tab1 complete")


